package com.zoweunion.mechanic.controller.base;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.dao.FacilitatorPersonnelRelationDao;
import com.zoweunion.mechanic.entity.*;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.plugins.mq.RabbitMQCustomer;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.base.LockCarService;
import com.zoweunion.mechanic.service.base.OwnerService;
import com.zoweunion.mechanic.service.base.UserService;
import com.zoweunion.mechanic.util.ExcelUtils;
import com.zoweunion.mechanic.util.HttpClient;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.Orgin;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.task.CarDataAbnormalTask;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * 车主管理控制层
 * @author Administrator
 */
@RestController
@RequestMapping("/owner")
@SuppressWarnings("unchecked")
public class OwnerController extends BaseController{
	
	@Autowired
	private OwnerService ownerService;

	@Autowired
	private AppService appService;

	@Autowired
	private RabbitMQCustomer rabbitMQCustomer;

	@Autowired
	private UserService userService;

	@Autowired
	private LockCarService lockCarService;

	@Autowired
	private CarDataAbnormalTask carDataAbnormalTask;

	@Autowired
	private FacilitatorPersonnelRelationDao facilitatorPersonnelRelationDao;

	/**
	 * 管理员给车主添加车辆
	 * @param str  包含车主id 物联网卡编号  物联网卡路径   要添加的车辆数据
	 */
	@PostMapping("/addCar")
	public ResponseBean addCar(@RequestBody String str,HttpServletRequest request){
		logBefore(logger, "车主管理_添加车辆");
		ResponseBean responseBean = new ResponseBean();
		int code = Constants.CODE_ERROR;
		String message = "添加车辆失败";
		
		try {
			Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);
			reqMap.put("s_id", getCurrentUser(request).getS_id());
			reqMap.put("update_user", getCurrentUser(request).getId());
			reqMap.put("create_user", getCurrentUser(request).getId());
			reqMap.put("user_name", getCurrentUser(request).getUser_name());
			int result = ownerService.addCar(reqMap);
			if(result>0){
				code = Constants.CODE_SUCCESS;
				message = "添加车辆成功";
			}else{
				code = Constants.CODE_HANDEL_FAILED;
			}
		}catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			responseBean.setCode(code);
			responseBean.setMessage(message);
			logAfter(logger); 
		}
		return responseBean;
	}


	//todo 临时接口
	@PostMapping("/testCar")
	public ResponseBean upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws Exception {
		ImportParams params = new ImportParams();
		List<ThingsIdBean> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
				ThingsIdBean.class, params);
		for (ThingsIdBean item : result) {
			Map<String,Object> reqMap = new HashMap<>();
			reqMap.put("advice_name","test-"+item.getThings_id());
			reqMap.put("things_id",item.getThings_id());
			reqMap.put("brand","-");
			reqMap.put("car_no","-");
			reqMap.put("car_type","-");
			reqMap.put("engine_no","-");
			reqMap.put("fuel_tank","-");
			reqMap.put("model","-");
			reqMap.put("buy_time","2020-11-30");
			reqMap.put("has_lock_car","0");
			reqMap.put("engine_name_id","a40c30341d224e9d9fedb0d54763c4a6");
			reqMap.put("id","54d2772466344a38b732bcc90266688c");
			reqMap.put("s_id", "6bd970ddd3e44e0f8646f951453ce18e");
			ownerService.addCar(reqMap);
		}
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
	}




	/**
	 * 管理员给车主编辑车辆
	 * @param str   车辆id   要编辑的车辆数据
	 * @throws MyException 
	 */
	@PostMapping("/editCar")
	public ResponseBean editCar(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主管理_编辑车辆");
		Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("update_user", getCurrentUser(request).getId());
		reqMap.put("user_name", getCurrentUser(request).getUser_name());
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		int result = ownerService.editCar(reqMap);
		if(result>0){
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
		}
		return new ResponseBean(Constants.CODE_HANDEL_FAILED,"编辑失败",null);
	}

    /**
	 * 服务商-申请账期
	 * @param request
	 * @param str
	 * @throws MyException
	 */
	@Transactional(rollbackFor = Exception.class)
	@PostMapping("/applyAccountingPeriod")
	public ResponseBean applyAccountingPeriod(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "服务商-申请账期");
		Map<String,Object> reqMap = JSONObject.parseObject(str,Map.class);
		int count = ownerService.selectApplyAccountingPeriod(reqMap);
		if(count == 0) {
			String userId = getCurrentUser(request).getId();
			reqMap.put("create_user", userId);
			reqMap.put("update_user", userId);
			//新增待审核
			reqMap.put("status", 0);
			//添加到车辆账期
			int result = ownerService.applyAccountingPeriod(reqMap);
			//添加申请记录
			int resultRecord = ownerService.addApplyAccountingPeriodRecord(reqMap);
			result = result + resultRecord;
			if (result == 2) {
				return new ResponseBean(Constants.CODE_SUCCESS, "申请成功！", null);
			} else {
				return new ResponseBean(Constants.CODE_ERROR, "申请失败！", null);
			}
		}
		return new ResponseBean(Constants.CODE_ERROR, "该车辆已经申请过不可重复申请！", null);
	}

	/**
	 * 金融平台：查询申请账期记录
	 * @param car_id
	 */
	@GetMapping("/selectApplyAccountingPeriodRecord")
	public ResponseBean selectApplyAccountingPeriodRecord(@RequestParam String car_id) throws MyException{
		logBefore(logger, "服务商-查询申请账期记录");
		Map<String, Object> reqMap = new HashMap<>();
		reqMap.put("car_id",car_id);
		List<Map<String, Object>> recordList = ownerService.selectApplyAccountingPeriodRecord(reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS,"查询申请记录成功！",recordList);
	}

	/**
	 * 金融平台：生成账期前页面预览
	 * @param str
	 * @return
	 */
	@PostMapping("/previewAccountingPeriod")
	public ResponseBean previewAccountingPeriod(@RequestBody String str,HttpServletRequest request) throws MyException {
		logBefore(logger, "金融平台-预览账期");
		Map<String,Object> reqMap = JSONObject.parseObject(str,Map.class);
		List<String> list = new ArrayList<>();
		String startDate = reqMap.get("start_date").toString();
		String endDate = reqMap.get("end_date").toString();
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime startTime = LocalDateTime.parse(startDate, df);
		LocalDateTime withlastDayOfMonthForStartTime = startTime.with(TemporalAdjusters.lastDayOfMonth());
		LocalDateTime endTime = LocalDateTime.parse(endDate, df);
		int payment_interval = Integer.valueOf(reqMap.get("payment_interval").toString());

		int dayOfMonthOfStartTime = startTime.getDayOfMonth();
		int dayOfMonthOfWithlastDayOfMonthForStartTime = withlastDayOfMonthForStartTime.getDayOfMonth();
		int repayment_day = Integer.valueOf(reqMap.get("repayment_day").toString());
		boolean isNeedToNextMonth; // 是否需要月份加 1
		if(dayOfMonthOfStartTime <= repayment_day && repayment_day <= dayOfMonthOfWithlastDayOfMonthForStartTime) {
			isNeedToNextMonth = false;
		} else {
			isNeedToNextMonth = true;
		}

		int total_period = Integer.valueOf(reqMap.get("total_period").toString());
		int count = (int) (Math.floor(total_period / payment_interval));
		int last = total_period % payment_interval;
		for (int i = 0; i < count; i++) {
			LocalDateTime payment_datetime;
			if(isNeedToNextMonth) {
				payment_datetime = startTime.plusMonths((i + 1) * payment_interval).withDayOfMonth(repayment_day);
			} else {
				payment_datetime = startTime.plusMonths(i * payment_interval).withDayOfMonth(repayment_day);
			}

			reqMap.put("payment_datetime", payment_datetime);
			list.add(payment_datetime.toString());
		}
		if (last > 0) {
			LocalDateTime payment_datetime = endTime.withDayOfMonth(repayment_day);
			reqMap.put("payment_datetime", payment_datetime);
			list.add(payment_datetime.toString());
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"预览账期",list);
	}

	/**
	 * 金融平台：审核账期 以及 服务商重新申请
	 * @param str
	 * @return null
	 */
    @Transactional(rollbackFor = Exception.class)
	@PostMapping("/updateAccountingPeriod")
	public ResponseBean updateAccountingPeriod(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "金融平台-更新(审核)账期");
		Map<String,Object> reqMap = JSONObject.parseObject(str,Map.class);
		String userId = getCurrentUser(request).getId();
		reqMap.put("create_user", userId);
		reqMap.put("update_user",userId);
		Map<String, Object> accountInfo = ownerService.selectAccountingPeriodInfo(reqMap);
		int result = 0;
		int resultRecord = 0;
		if (accountInfo != null && Integer.valueOf(accountInfo.get("status").toString()) == 0) {
			//修改车辆账期
			result = ownerService.updateAccountingPeriod(reqMap);
			//添加审核记录
			resultRecord = ownerService.addApplyAccountingPeriodRecord(reqMap);
			//如果status = 1 则通过该申请，则需要生成还款单
			if (reqMap.get("status") != null && Integer.valueOf(reqMap.get("status").toString()) == 1) {
				if (accountInfo != null) {
					String startDate = accountInfo.get("start_date").toString().substring(0, accountInfo.get("start_date").toString().length() - 2);
					String endDate = accountInfo.get("end_date").toString().substring(0, accountInfo.get("end_date").toString().length() - 2);
					DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
					LocalDateTime startTime = LocalDateTime.parse(startDate, df);
					LocalDateTime withlastDayOfMonthForStartTime = startTime.with(TemporalAdjusters.lastDayOfMonth());
					LocalDateTime endTime = LocalDateTime.parse(endDate, df);
					int payment_interval = Integer.valueOf(accountInfo.get("payment_interval").toString());
					int dayOfMonthOfStartTime = startTime.getDayOfMonth();
					int dayOfMonthOfWithlastDayOfMonthForStartTime = withlastDayOfMonthForStartTime.getDayOfMonth();
					int repayment_day = Integer.valueOf(accountInfo.get("repayment_day").toString());
					boolean isNeedToNextMonth; // 是否需要月份加 1
					if(dayOfMonthOfStartTime <= repayment_day && repayment_day <= dayOfMonthOfWithlastDayOfMonthForStartTime) {
						isNeedToNextMonth = false;
					} else {
						isNeedToNextMonth = true;
					}
					int total_period = Integer.valueOf(accountInfo.get("total_period").toString());
					int count = (int) (Math.floor(total_period / payment_interval));
					int last = total_period % payment_interval;
					for (int i = 0; i < count; i++) {
						LocalDateTime payment_datetime;
						if(isNeedToNextMonth) {
							payment_datetime = startTime.plusMonths((i + 1) * payment_interval).withDayOfMonth(repayment_day);
						} else {
							payment_datetime = startTime.plusMonths(i * payment_interval).withDayOfMonth(repayment_day);
						}
						reqMap.put("payment_datetime", payment_datetime);
						ownerService.insertRepaymentStatement(reqMap);
					}
					if (last > 0) {
						LocalDateTime payment_datetime = endTime.withDayOfMonth(repayment_day);
						reqMap.put("payment_datetime", payment_datetime);
						ownerService.insertRepaymentStatement(reqMap);
					}
				}
			}
			//如果status =2 或者 3 并且参数status 为0 则是被拒绝或者废弃重新申请
		}else if(accountInfo != null && (Integer.valueOf(accountInfo.get("status").toString()) == 2 || Integer.valueOf(accountInfo.get("status").toString()) == 3)
				&& reqMap.get("status") != null && Integer.valueOf(reqMap.get("status").toString()) == 0) {
			reqMap.put("status","0");
			//修改车辆账期
			result = ownerService.updateAccountingPeriod(reqMap);
			//添加审核记录
			resultRecord = ownerService.addApplyAccountingPeriodRecord(reqMap);
			//如果status=1 参数status=3 则是申请通过后被废弃
		}else if(accountInfo != null && Integer.valueOf(accountInfo.get("status").toString()) == 1
				&& reqMap.get("status") != null && Integer.valueOf(reqMap.get("status").toString()) == 3) {
			//修改车辆账期
			result = ownerService.updateAccountingPeriod(reqMap);
			//添加审核记录
			resultRecord = ownerService.addApplyAccountingPeriodRecord(reqMap);
			//删除生成的账期
			ownerService.deleteRepaymentStatement(reqMap);
		}
		result = result + resultRecord;
		if(result == 2) {
			return new ResponseBean(Constants.CODE_SUCCESS, "操作成功！", null);
		}else{
			return new ResponseBean(Constants.CODE_ERROR, "操作失败！", null);
		}
	}

	/**
	 * 金融平台：锁车管理-查询车辆的还款账单
	 * @param car_id
	 * @return repaymentStatementList
	 */
	@GetMapping("/selectRepaymentStatement")
	public ResponseBean selectRepaymentStatement(@RequestParam("car_id") String car_id,HttpServletRequest request) throws MyException{
		Map<String, Object> reqMap = new HashMap<>();
		reqMap.put("car_id", car_id);
		List<Map<String, Object>> repaymentStatementList = ownerService.selectRepaymentStatement(reqMap);
		if(repaymentStatementList.size() > 0){
			repaymentStatementList.forEach(item -> {
				reqMap.put("parent_id",item.get("id").toString());
				List<Map<String, Object>> subRepaymentStatementList = ownerService.selectRepaymentStatement(reqMap);
				if(subRepaymentStatementList.size() > 0) {
					item.put("subRepaymentStatement", subRepaymentStatementList);
				}
				item.put("current_datetime", new Date());
			});
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"查询成功！", repaymentStatementList);
	}

    /**
	 * 金融平台：锁车管理-手动设置是否已还款
	 */
	@PostMapping("/updateRepaymentStatement")
	public ResponseBean updateRepaymentStatement(@RequestBody Map<String, Object> reqMap,HttpServletRequest request) throws MyException{
		User currentUser = getCurrentUser(request);
		String userId = currentUser.getId();
		reqMap.put("create_user", userId);
		 ownerService.updateRepaymentStatement(reqMap);
		// 已还款则调用解锁
		if(Integer.valueOf(reqMap.get("status").toString()) == 1) {
			reqMap.put("lock_user_id", userId);
			reqMap.put("update_user", userId);
			reqMap.put("s_id", currentUser.getS_id());
			reqMap.put("user_name", currentUser.getUser_name());
           lockCarService.thingsIdCarOperation(reqMap);

			// 完成还款，发送给车主，APP极光消息提醒
			Map<String, Object> carMap = facilitatorPersonnelRelationDao.getCarInfoWithOwnerInfo(Orgin.getString(reqMap, "car_id"));
			carDataAbnormalTask.jPushAccountingPeriod(carMap);
		}

		if(reqMap.get("parent_id") != null && reqMap.get("parent_id").toString() != "") {
			//List<Map<String, Object>> subRepaymentStatementList = ownerService.selectRepaymentStatement(reqMap);
//			if(subRepaymentStatementList.size() > 0) {
//				Map<String, Object> subRepaymentStatement = subRepaymentStatementList.get(subRepaymentStatementList.size() - 1);
//				String date1 = subRepaymentStatement.get("payment_datetime").toString().substring(0, subRepaymentStatement.get("payment_datetime").toString().length() - 2);;
//				String date2 = reqMap.get("payment_datetime").toString();
//				DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			//	LocalDate startTime = LocalDate.parse(date1, df);
//				LocalDate endTime = LocalDate.parse(date2, df);
//				if(endTime.isAfter(startTime)) {
//					ownerService.insertRepaymentStatement(reqMap);
//				} else {
//					return new ResponseBean(Constants.CODE_ERROR,"时间设置需要大于最近一次延期时间！", null);
//				}
//			} else {
				ownerService.insertRepaymentStatement(reqMap);
//			}

			// 补缴欠款成功，发送给车主，APP极光消息提醒
			Map<String, Object> carMap = facilitatorPersonnelRelationDao.getCarInfoWithOwnerInfo(Orgin.getString(reqMap, "car_id"));
			carDataAbnormalTask.jPushSupplementaryPayment(carMap);
		}

		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功！", null);
	}

	/**
	 * 解绑车辆
	 * @param str  带有  车辆id 物联网卡编号
	 * @throws MyException
	 */
	@PostMapping("/unbind")
	public ResponseBean unbind(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主管理_解绑车辆");
		Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);
		User user = getCurrentUser(request);
		reqMap.put("update_user", user.getId());
		reqMap.put("s_id", user.getS_id());
		int result = ownerService.unbind(reqMap);
		if(result>0){
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
		}
		return new ResponseBean(Constants.CODE_HANDEL_FAILED,"解绑失败",null);
	}

	/**
	 * 服务商树形结构展示
	 * @param request
	 * @return 树形服务商信息
	 */
    @PostMapping("/serverList")
	public ResponseBean serverList(HttpServletRequest request) throws MyException{
		logBefore(logger, "服务商_树形展示");
		Map<String,Object> reqMap = new HashMap<>();
		reqMap.put("create_sid",getCurrentUser(request).getS_id());
		List<FacilitatorEntity> facilitatorEntityList = ownerService.getFacilitatorList(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",facilitatorEntityList);
	}
	
	/**
	 * 车主列表展示 (分页,条件查询)
	 * @param str 分页条件 查询条件(车主姓名,电话)
	 * @param request
	 * @return 车主信息 包含已拥有车辆数
	 */
	@PostMapping("/list")
	public ResponseBean list(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主管理_列表展示");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User user = getCurrentUser(request);
		// 拦截器处理数据范围需要的参数-start
		if(reqMap.get("s_id") == null || reqMap.get("s_id") == ""){
			reqMap.put("s_id", user.getS_id());
		}
		reqMap.put("current_logined_user_id", user.getId());
		reqMap.put("current_logined_user_r_id", user.getR_id());
		// 拦截器处理数据范围需要的参数-end
		Map<String, Object> resultMap=ownerService.getPageQuery(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}
	
	/**
	 * @param str 车主id
	 */
	@PostMapping("/carsList")
	public ResponseBean carsList(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主管理_车主拥有车辆展示");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		if(reqMap.get("s_id") == null || reqMap.get("s_id") == ""){
			reqMap.put("s_id", getCurrentUser(request).getS_id());
		}
		//reqMap.put("o_id", reqMap.get("id").toString());
		List<Map<String, Object>> resultMap=ownerService.getCarsByOid(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	@GetMapping("/exportCarsLockRecord")
	public void exportCarsLockRecord(@RequestParam Map<String,Object> reqMap,HttpServletRequest request,HttpServletResponse response) throws MyException, IOException {
		logBefore(logger, "锁车管理_锁车记录导出");
		List<CarsLockRecordEntity> carsLockRecordEntityList = new ArrayList<>();
		//reqMap.put("s_id", getCurrentUser(request).getS_id());
		Map<String, Object> resultMap=ownerService.getPageQuery(reqMap);
		List<Map<String,Object>> ownerList =(List<Map<String,Object>>)resultMap.get("list");
		if(ownerList.size() > 0) {
			ownerList.forEach((ownerItem)-> {
				CarsLockRecordEntity carsLockRecordEntity =new CarsLockRecordEntity();
				carsLockRecordEntity.setId(ownerItem.get("id").toString());
				carsLockRecordEntity.setUserName(ownerItem.get("user_name").toString());
				carsLockRecordEntity.setStatus(Integer.valueOf(ownerItem.get("status").toString()));
				carsLockRecordEntity.setMobile_phone(ownerItem.get("mobile_phone").toString());
				List<DriverEntity> driverEntityList = new ArrayList<>();
				Map<String, Object> hashMap = new HashMap<>();
				hashMap.put("o_id", ownerItem.get("id").toString());
				hashMap.put("hasLockCar", 1);
				hashMap.put("s_id", reqMap.get("s_id"));
				List<Map<String, Object>> carList = ownerService.getCarsByOid(hashMap);
				if(carList.size() > 0) {
					carList.forEach(carItem -> {
						DriverEntity driverEntity = new DriverEntity();
						driverEntity.setId(carItem.get("id").toString());
						driverEntity.setUser_name(carItem.get("user_name").toString());
						driverEntity.setMobile_phone(carItem.get("mobile_phone").toString());
						driverEntity.setAdvice_name(carItem.get("advice_name").toString());
						driverEntity.setBrand(carItem.get("brand").toString());
						driverEntity.setManufacturing_num(carItem.get("manufacturing_num") == null ? "" : carItem.get("manufacturing_num").toString());
						driverEntity.setModel(carItem.get("model").toString());
						driverEntity.setThings_id(carItem.get("things_id").toString());
						driverEntity.setBuy_time(carItem.get("buy_time") == null ? "" : carItem.get("buy_time").toString());
						driverEntity.setMonitor_state(Integer.valueOf(carItem.get("monitor_state").toString()));
						List<LockCarEntity> lockCarEntityList = new ArrayList<>();
						Map<String, Object> paraMap = new HashMap<>();
						paraMap.put("car_id", carItem.get("id"));
						paraMap.put("things_id", carItem.get("things_id"));
						List<Map<String, Object>> recordList = lockCarService.thingsIdCarRecord(paraMap);
						if(recordList.size() > 0){
							recordList.forEach(recordItem -> {
                               LockCarEntity lockCarEntity = new LockCarEntity();
								lockCarEntity.setId(recordItem.get("id").toString());
								lockCarEntity.setUser_name(recordItem.get("user_name").toString());
								lockCarEntity.setUpdate_time(recordItem.get("update_time").toString());
								lockCarEntity.setLock_type(Integer.valueOf(recordItem.get("lock_type").toString()));
								lockCarEntityList.add(lockCarEntity);
							});
						}
						driverEntity.setLockCarEntityList(lockCarEntityList);
						driverEntityList.add(driverEntity);
					});
				}
				carsLockRecordEntity.setDriverEntityList(driverEntityList);
				carsLockRecordEntityList.add(carsLockRecordEntity);
			});
		}


		logAfter(logger);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("锁车记录表","锁车记录"),
				 CarsLockRecordEntity.class, carsLockRecordEntityList);
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-Type", "application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("锁车记录", "UTF-8") + ".xls");
		ServletOutputStream out = response.getOutputStream();
		workbook.write(out);
		out.flush();

		FileOutputStream fos = new FileOutputStream("C:/Users/Administrator/Desktop/下载/carsLockRecordEntityList.tt.xls");
		workbook.write(fos);
		fos.close();
		//return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",carsLockRecordEntityList);
	}


    /**
     * @param reqMap
     */
    @PostMapping("/carsFirst")
    public ResponseBean carsFirst(@RequestBody Map<String, Object> reqMap){
        logBefore(logger, "车主管理_车主拥有车辆展示");
        String result = ownerService.getFirstBySid(reqMap);
        logAfter(logger);
        if (null != result) {
            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
        } else {
            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", "");
        }
    }
	 
	/**
	 * 获取未绑定的物联网卡列表  分页条件 和物联网编号查询条件
	 */
	@PostMapping("/thingsList")
	public ResponseBean thingsList(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主管理_未绑定物联网卡展示");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		Map<String, Object> resultMap=ownerService.getThingsList(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}
	
	
	
	
	/**
	 * 删除车主
	 */
	@PostMapping("/delete")
	public ResponseBean delete(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主管理_删除车主");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		reqMap.put("current_user_id", getCurrentUser(request).getId());
		reqMap.put("user_name", getCurrentUser(request).getUser_name());
		int result=ownerService.deleteOwner(reqMap);
		logAfter(logger);
		if(result<=0) {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}

	/**
	 * 车辆转移
	 */
	@PostMapping("/updateCarInfoById")
	public ResponseBean updateCarInfoById(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主管理_车辆转移");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		reqMap.put("current_user_id", getCurrentUser(request).getId());
		ownerService.updateCarInfoById(reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功","");
	}
	
	/**
	 * 查询车辆位置 
	 * @param str 车辆的opc_path
	 * @return 车辆的经纬度
	 */
	@PostMapping("/getOneCarLocation")
	public ResponseBean getOneCarLocation(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主管理_获取指定车辆位置");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		Map<String,Object> resultMap=ownerService.getOneCarLocation(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 查询车辆位置
	 * @param str 车辆的opc_path
	 * @return 车辆的经纬度
	 */
	@PostMapping("/getOneCarLocationNew")
	public ResponseBean getOneCarLocationNew(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主管理_获取指定车辆位置");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		Map<String,Object> resultMap=ownerService.getOneCarLocationNew(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}
	
	/**
	 * 查询车辆位置 -车辆坐标
	 * @param 
	 * @return 车辆的经纬度
	 */
	@PostMapping("/getAllCarList")
	public ResponseBean getAllCarList(@RequestBody String str, HttpServletRequest request)throws MyException{
		logBefore(logger, "获取服务商下所有车辆");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		List<Map<String, Object>> resultMap = ownerService.getAllCarList(reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}
	
	/**
	 * 查询车辆位置 -坐标
	 * @param 
	 * @return 车辆的经纬度
	 */
	@PostMapping("/getAllCarLocation")
	public ResponseBean getAllCarLocation(HttpServletRequest request)throws MyException{
		logBefore(logger, "车主管理_获取服务商下所有车辆位置");
		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		List<Map<String, Object>> resultList=ownerService.getAllCarLocation(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultList);
	}

	/**
	 * 查询车辆位置 -坐标 分页
	 * @param
	 * @return 车辆的经纬度
	 */
	@PostMapping("/getAllCar")
	public ResponseBean getAllCar(@RequestBody String str, HttpServletRequest request)throws MyException{
		logBefore(logger, "车主管理_获取服务商下所有车辆位置 分页");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		reqMap.put("current_login_user_id", getCurrentUser(request).getId());
		//民生银行账户演示临时添加数据
//		if(reqMap.get("s_id").toString().equals("12d6e455b7d747e39b7466b35e34af21") || reqMap.get("s_id").toString().equals("3c336fa092c24b39a8f2253ddf7a2220")) {
//			reqMap.put("demo_sid",Constants.DEMO_ACCOUNT_S_ID[0]);
//		}
		Map<String, Object> resultMap=ownerService.getAllCar(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}
	
	/**
	 * 调用新思联接口获取车辆实时信息
	 * @param 
	 * @return 车辆的信息
	 */
	@PostMapping("/getCarInfo")
	public ResponseBean getCarInfo(HttpServletRequest request)throws MyException{
		logBefore(logger, "调用新思联接口获取车辆实时信息");
		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		List<Map<String,Object>> carsList = ownerService.getCars(reqMap);
		List<String> carResultList = new ArrayList<String>();
		for (Map<String, Object> map : carsList) {
			//拼接参数
			String opcpathUrl = Constants.THINGS_URL_ONE+map.get("opc_path").toString();
			//调用新思联接口
			String carResult = HttpClient.doGet(opcpathUrl,Constants.interface_account, Constants.unify_account);
			carResultList.add(carResult);
		}
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result",carResultList);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}


	/**
	 *  车辆轨迹
	 * @param str {c_id:车辆id， }
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/trajectory")
	public ResponseBean trajectory(@RequestBody String str, HttpServletRequest request) {
		logBefore(logger, "车辆轨迹");
		Map<String, Object> trajectoryMap = null;
		try {
			Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
			trajectoryMap = appService.getTrajectory(reqMap);
		} catch (Exception e) {
			return new ResponseBean(Constants.CODE_ERROR,"操作失败",trajectoryMap);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",trajectoryMap);
	}
	/**
	 * 调用新思联接口获取车辆实时信息
	 * @param
	 * @return 车辆的信息
	 */
	@PostMapping("/getRunningRecord")
	public ResponseBean getRunningRecord(@RequestBody String str,HttpServletRequest request)throws MyException{
		logBefore(logger, "调用新思联接口获取车辆实时信息");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		if(!reqMap.containsKey("startTime")){
			Calendar c = Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.DAY_OF_MONTH, -7);
			reqMap.put("startTime", df.format(c.getTime()));
			reqMap.put("endTime", df.format(new Date()));
		}
		String time = null;
		try {
			time = "startTime="+ URLEncoder.encode(reqMap.get("startTime").toString(),"utf-8")+"&endTime="+URLEncoder.encode(reqMap.get("endTime").toString(),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		StringBuilder opcpathUrl = new StringBuilder();
		opcpathUrl.append(Constants.THINGS_HIS_URL+"NodeFullTag="+reqMap.get("opc_path").toString()+"&istree=false&");
		opcpathUrl.append(time);

		Map<String, Object> resultMap = new HashMap<>();
		Map<String, Object> cacheMap = new HashMap<>();
		List dataName=new ArrayList();
		List dataValue=new ArrayList();

		JSONObject things = JSONObject.parseObject(HttpClient.doGet(
				opcpathUrl.toString(),
				Constants.interface_account, Constants.unify_account));
		if(null!=things){
			JSONObject nodeData = (JSONObject)((JSONArray) things.get("node")).get(0);
			List<Map<String,Object>> datalist= (List<Map<String, Object>>) nodeData.get("datalist");
			for(Map<String, Object> data:datalist){
				dataValue.add(data.get("OperatingHours"));
				dataName.add(data.get("DataTime").toString().substring(0,10));

//				Map<String,Object> map=new HashMap<>();
//				map.put("GPSlongitude",data.get("GPSlongitude"));
//				map.put("GPSlatitude",data.get("GPSlatitude"));
//				map.put("DataTime",data.get("DataTime"));
			}


		}
//		Collections.reverse(dataValue);
		List dataNameTo=new ArrayList();
		List dataValueTo=new ArrayList();
		for(int i=dataName.size()-1;i>=0;i--){
			if(!dataNameTo.contains(dataName.get(i))){
				dataNameTo.add(dataName.get(i));
				dataValueTo.add(dataValue.get(i));
			}
		}
		resultMap.put("dataValue",dataValueTo);
		resultMap.put("dataName",dataNameTo);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 查询车辆位置 -坐标
	 * @param
	 * @return 车辆列表
	 */
	@PostMapping("/getAllCarLocationNew")
	public ResponseBean getAllCarLocationNew(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "车主管理_获取服务商下所有车辆位置");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		reqMap.put("s_id", currentUser.getS_id());
		//民生银行临时添加数据
//		if(currentUser.getS_id().equals("12d6e455b7d747e39b7466b35e34af21") || reqMap.get("s_id").toString().equals("3c336fa092c24b39a8f2253ddf7a2220")){
//			reqMap.put("demo_sid",Constants.DEMO_ACCOUNT_S_ID[0]);
//		}
		Map<String, Object> resultList = ownerService.getAllCarLocationNew(currentUser, reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultList);
	}

	/**
	 * 查询车辆位置 -坐标
	 * @param
	 * @return 车辆列表
	 */
	@PostMapping("/getCarRealData")
	public ResponseBean getCarRealData(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "车主管理_获取服务商下所有车辆位置");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		reqMap.put("s_id", currentUser.getS_id());
		Map<String, Object> resultMap = ownerService.getCarRealData(currentUser, reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
	}

	/**
	 * 车辆监管 获取运行记录
	 * @param
	 * @return 车辆的信息
	 */
	@PostMapping("/getRunningRecordNew")
	public ResponseBean getRunningRecordNew(@RequestBody String str,HttpServletRequest request)throws MyException{
		logBefore(logger, "车辆接管 获取运行记录");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		Map<String, Object> runMap = ownerService.getRunningRecordNew(currentUser, reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功", runMap);
	}

	/**
	 * 车辆监管 获取数据列表
	 * @param
	 * @return 车辆的信息
	 */
	@PostMapping("/carHistoricalDataPCNew")
	public ResponseBean carHistoricalDataPCNew(@RequestBody String str,HttpServletRequest request)throws MyException{
		logBefore(logger, "车辆接管 获取数据列表");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		Map<String, Object> runMap = ownerService.carHistoricalDataPCNew(currentUser, reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功", runMap);
	}

	/**
	 * 车辆监管 获取指标列表
	 * @param
	 * @return 车辆的信息
	 */
	@PostMapping("/listIndex")
	public ResponseBean listIndex(@RequestBody String str,HttpServletRequest request)throws MyException{
		logBefore(logger, "车辆接管 获取指标列表");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		List<Map<String, Object>> runMap = ownerService.listIndex(currentUser, reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功", runMap);
	}

	/**
	 * 车辆监管 获取指标列表
	 * @param
	 * @return 车辆的信息
	 */
	@PostMapping("/carHistoricalDataLineNew")
	public ResponseBean carHistoricalDataLineNew(@RequestBody String str,HttpServletRequest request)throws MyException{
		logBefore(logger, "车辆接管 获取指标列表");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		Map<String, Object> runMap = ownerService.carHistoricalDataLineNew(currentUser, reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功", runMap);
	}

	@PostMapping("/getLockInfo")
	public ResponseBean getLockInfo(HttpServletRequest request) throws MyException{
		logBefore(logger, "获取申请解锁的列表");
		Map<String, Object> reqMap = new HashMap<>();
		User currentUser = getCurrentUser(request);
        reqMap.put("user_id",currentUser.getId());
		List<Map<String,Object>> lockInfo = appService.getLockInfo(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",lockInfo);
	}
	@PostMapping("/getLockInfoStatus")
	public ResponseBean getLockInfoStatus(HttpServletRequest request) throws MyException{
		logBefore(logger, "获取申请解锁的列表状态");
		Map<String, Object> reqMap = new HashMap<>();
		int lockInfoStatus = appService.getLockInfoStatus(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",lockInfoStatus);
	}

    /**
     * 获取发动机名称表
     * @return
     */
    @PostMapping("/engineNameList")
    public ResponseBean engineNameList() {
        logBefore(logger, "发动机名称列表");
        List<Map<String, Object>> reqMap = new ArrayList<>();
        reqMap = ownerService.getEngineNameList();
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",reqMap);
    }

    /**
     * 车主列表分页(暂时未被使用)
     * @return
     */
    @PostMapping("/ownerList")
    public ResponseBean ownerList(@RequestBody Map<String, Object> reqMap, HttpServletRequest request) throws MyException {
        logBefore(logger, "车主列表分页");
        reqMap.put("s_id", getCurrentUser(request).getS_id());
        reqMap.put("r_id", Constants.ROLE_CZ);
        PageInfo info = ownerService.getOwnerList(reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",info);
    }

    /**
     *车辆列表含条件
     */
    @PostMapping("/carsListNew")
    public ResponseBean carsListNew(@RequestBody Map<String, Object> reqMap,HttpServletRequest request) throws MyException{
        logBefore(logger, "车辆列表含条件");
		if(reqMap.get("s_id") == null || reqMap.get("s_id") == ""){
			reqMap.put("s_id", getCurrentUser(request).getS_id());
		}
        PageInfo info = ownerService.getCarsByOidNew(reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",info);
    }

    /**
     * 车辆信息导出
     *
     * */
    @GetMapping("/carsListExport")
    public void carsListExport (@RequestParam Map<String, Object> reqMap, HttpServletResponse response) throws Exception {
        logBefore(logger, "车辆信息导出");
        List<CarListBean> carsListExport = ownerService.carsListExport(reqMap);
        String serverName = ownerService.getServerName(reqMap);
        logAfter(logger);
        ExcelUtils.exportExcelToTarget(response, serverName+"-车辆信息", carsListExport, CarListBean.class);
    }

}
